package hz.mobileproject.pda.ui.activity.work;

import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.czt.mp3recorder.MP3Recorder;
import com.google.gson.Gson;
import com.shuyu.waveview.FileUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import cn.droidlover.xdroidmvp.mvp.XActivity;
import cn.droidlover.xdroidmvp.router.Router;
import hz.mobileproject.pda.R;
import hz.mobileproject.pda.broadcast.HandleBroadcast;
import hz.mobileproject.pda.broadcast.IShowBarcodeStr;
import hz.mobileproject.pda.entity.CardBean;
import hz.mobileproject.pda.entity.CardBeans;
import hz.mobileproject.pda.entity.request.Request_Edu_inter;
import hz.mobileproject.pda.entity.request.Request_loadPersioneInfo;
import hz.mobileproject.pda.entity.request.Request_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.Response_loadSub_data;
import hz.mobileproject.pda.entity.response.Response_loadType;
import hz.mobileproject.pda.event.VoiceManager;
import hz.mobileproject.pda.listener.ICommonV;
import hz.mobileproject.pda.listener.VoiceCallBack;
import hz.mobileproject.pda.presenter.PEdu;
import hz.mobileproject.pda.ui.adapter.TeAdapter;
import hz.mobileproject.pda.ui.view.LoadingDialog;

import static com.blankj.utilcode.constant.TimeConstants.MSEC;

public class Edu_upload_test_Activity extends XActivity<PEdu> implements ICommonV ,IShowBarcodeStr {

    private LinearLayout mLayoutRecord;
    private RelativeLayout mLayoutPlay;
    private VoiceManager voiceManager;
    private String mRecPath = "";
    private HandleBroadcast handleBroadcast;
    private SoundPool soundpool;
    private int soundid;
    private LoadingDialog loadingDialog;
    private SPUtils spUtils_cusNumber;
    private String cusNumber;
    private String policeCode;
    private String persionId;
    private String police_id;
    private String police_name;
    private String prisoner_name;
    private TextView tv_policeName;
    private TextView tv_policeID;
    private TextView tv_prisonerName;
    private JSONArray danger_evaluate;
    private JSONArray talk_classify;
    private JSONArray talk_effect;
    private JSONArray emotion_evaluate;
    private List<Response_loadType> loadTypes;
    private List<Response_loadSub_data> sublist;
    private String department_id;
    private String department_name;
    private Response_loadType loadType;
    public Request_Edu_inter inter;

    private List<CardBeans> cardItem = new ArrayList<>();
    private List<CardBeans> cardItem_ = new ArrayList<>();
    private List<CardBeans> cardItem_ss = new ArrayList<>();
    private List<CardBeans> cardItem_NO = new ArrayList<>();
    private List<CardBeans> cardItems = new ArrayList<>();
    private List<CardBeans> cardItemss = new ArrayList<>();
    private List<CardBeans> cardItemsss = new ArrayList<>();

    private Spinner spinner1;
    private TeAdapter mAdapter;
    private Spinner spinner2;
    private Spinner spinner3;
    private TeAdapter mAdapters;
    private TeAdapter mAdapterss;
    private TeAdapter mAdaptersss;
    private Spinner spinner0;
    private Spinner spinner01;
    private TeAdapter mAdapter_t;
    private Button loginButton;
    private TextView tv_prisonerID;
    private String time_check;
    private TextView tv_prisonerJibei;
    private boolean on_Off;
    private String now_time;
    private Spinner spinner11;
    private TeAdapter mAdapters_;
    private String filePath;
    private MP3Recorder mRecorder;

    public static void launch(Activity activity) {
        Router.newIntent(activity)
                .to(Edu_upload_test_Activity.class)
                .launch();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);





        mLayoutRecord = (LinearLayout) findViewById(R.id.layout_record);
        mLayoutPlay = (RelativeLayout) findViewById(R.id.layout_play);
        tv_policeName = (TextView) findViewById(R.id.tv_policeName);
        tv_policeID = (TextView) findViewById(R.id.tv_policeID);
        tv_prisonerID = (TextView) findViewById(R.id.tv_prisonerID);
        tv_prisonerName = (TextView) findViewById(R.id.tv_prisonerName);
        tv_prisonerJibei = (TextView) findViewById(R.id.tv_prisonerJibei);
        loginButton = (Button) findViewById(R.id.loginButton);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                String.valueOf(TimeUtils.getTimeSpanByNow(TimeUtils.getNowString(),MSEC));



                LogUtils.e(String.valueOf(TimeUtils.getTimeSpanByNow(now_time,MSEC)));
                Integer go=Integer.valueOf(String.valueOf(TimeUtils.getTimeSpanByNow(now_time,MSEC)));

                if (go<120000){
                    ToastUtils.showShort("谈话时长必须大于2分钟");

                    resolveStopRecord();
                }else {
                    loadingDialog.setMessage("数据加密传输中").show();
                    send_edu_data();
                }

            }
        });


        now_time= TimeUtils.getNowString();
        spinner0 = (Spinner) findViewById(R.id.spinner0);
        spinner01 = (Spinner) findViewById(R.id.spinner01);
        spinner1 = (Spinner) findViewById(R.id.spinner1);
        spinner11 = (Spinner) findViewById(R.id.spinner11);
        spinner2 = (Spinner) findViewById(R.id.spinner2);
        spinner3 = (Spinner) findViewById(R.id.spinner3);
        inter= new Request_Edu_inter();
        loadTypes= new ArrayList<>();
        voiceManager = new VoiceManager(Edu_upload_test_Activity.this, "/audio");

        voiceManager.setVoiceListener(new VoiceCallBack() {
            @Override
            public void voicePath(String path) {
                mRecPath = path;
                //获取配置接口
                visj();

            }

            @Override
            public void recFinish() {

            }

        });

        on_Off=true;

       /* mBtPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLayoutRecord.setVisibility(View.GONE);
                mLayoutPlay.setVisibility(View.VISIBLE);
                voiceManager.sessionPlay(true, mRecPath);
            }
        });*/

        showPromptDlg();

    }




    private void visj() {
        mLayoutRecord.setVisibility(View.GONE);
        mLayoutPlay.setVisibility(View.VISIBLE);
        voiceManager.sessionPlay(true, mRecPath);
    }





    private void showPromptDlg() {
        loadingDialog = new LoadingDialog(this);
        loadingDialog.setMessage("请扫描民警二维码").show();
    }

    @Override
    public void onWidgetClick(View view) {

    }

    @Override
    public void initData(Bundle savedInstanceState) {
    //初始化广播
        initScan();

    }

    private void initScan() {

        handleBroadcast = new HandleBroadcast(this, this);
        soundpool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
        soundid = soundpool.load("/etc/Scan_new.ogg", 1);

    }


    @Override
    protected void onResume() {
        super.onResume();
        try {




            spUtils_cusNumber = SPUtils.getInstance("app_login");
            cusNumber = spUtils_cusNumber.getString("cusnumber");
            handleBroadcast.sendMyBroadcast();

        } catch (Exception e) {


        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_education_talks;
    }

    @Override
    public PEdu newP() {
        return new PEdu(this);
    }



    @Override
    public void updateText(String msg) {
        LogUtils.e("扫描"+msg);
        soundpool.play(soundid, 1, 1, 0, 0, 1);
        boolean status = msg.contains("P");
        if (status&&on_Off){
           policeCode= msg.substring(1);
            Request_loadPoliceInfo loadPoliceInfo=  new Request_loadPoliceInfo();
            loadPoliceInfo.setCusNumber(cusNumber);
            loadPoliceInfo.setPoliceCode(policeCode);
            getP().loadData(loadPoliceInfo, 2,this);


            on_Off=false;
        }else {
            persionId=msg;
            Request_loadPersioneInfo loadPersioneInfo= new Request_loadPersioneInfo();
            loadPersioneInfo.setCusNumber(cusNumber);
            loadPersioneInfo.setPrisonerId(persionId);
            getP().loadData(loadPersioneInfo, 3,this);


            if (handleBroadcast != null) {
                handleBroadcast.overBroadcastReceiver(this);
            }
        }
    }



    @Override
    public void showError(Exception e) {

    }

    @Override
    public void showData(String s,int type) {
        JSONObject json= null;
        try {
            json = new JSONObject(s);
            switch (type){
                case 2://民警信息


                    getP().uploadData(4);

                    police_name=  json.getString("police_name");
                    police_id= json.getString("police_id");
                    department_id= json.getString("department_id");
                    department_name= json.getString("department_name");
                        loadingDialog.setMessage("请扫描罪犯二维码").show();
                    tv_policeName.setText(police_name);
                    tv_policeID.setText(policeCode);
                    break;
                case 3://罪犯信息
                        prisoner_name=  json.getString("prisoner_name");
                        time_check=  json.getString("time_check");
                        tv_prisonerName.setText(prisoner_name);
                    tv_prisonerID.setText(persionId);
                    tv_prisonerJibei.setText(time_check);
                        loadingDialog.dismiss();
                    //开始谈话
                    startTalk();
                    break;
                case 4://获取配置
                    Response_loadSub_data subData= new Response_loadSub_data();



                    talk_classify= json.getJSONArray("talk_classify");  //十必谈

                    for (int ss=0;ss<talk_classify.length();ss++){
                        JSONObject objects=talk_classify.getJSONObject(ss);
//                        options1Items.add(new ProvinceBean(ss,objects.getString("display_field"),objects.getString("display_value"),"其他数据"));
                        cardItem.add(new CardBeans(objects.getString("display_value"), objects.getString("display_field"),false));
                        CardBean cb = new CardBean(objects.getString("display_value"), objects.getString("display_field"));

                        JSONArray jj= objects.getJSONArray("sub_data");
                        if (jj.length()>0){
                            for (int oo=0;oo<jj.length();oo++){
                                JSONObject object= jj.getJSONObject(oo);
                                String    display_fields= object.getString("display_field");
                                String  display_values=object.getString("display_value");

                                cardItem_.add(new CardBeans(display_values, display_fields,false));
                            }

                        }

                    }

                    danger_evaluate= json.getJSONArray("danger_evaluate");  //危险
                    for(int i=0;i<danger_evaluate.length();i++){
                        JSONObject jsonobject=danger_evaluate.getJSONObject(i);
//                        loadType.setDisplay_field(jsonobject.getString("display_field"));
//                        loadType.setDisplay_value(jsonobject.getString("display_value"));
                        cardItems.add(new CardBeans(jsonobject.getString("display_value"), jsonobject.getString("display_field"),false));

                        JSONArray j= jsonobject.getJSONArray("sub_data");
                        if (j.length()>0){
                            sublist= new ArrayList<>();
                            for (int o=0;o<j.length();o++){
                                JSONObject object= j.getJSONObject(o);
                                String    display_fields= object.getString("display_field");

                                String  display_values=object.getString("display_value");

                                cardItem_ss.add(new CardBeans(display_values, display_fields,false));

                            }
//                            loadType.setSub_data(sublist);

                        }

//                        loadTypes.add(loadType);
                    }




                    talk_effect= json.getJSONArray("talk_effect");  //谈话评估
                    for (int ss=0;ss<talk_effect.length();ss++){
                        JSONObject objects=talk_effect.getJSONObject(ss);
                        cardItemss.add(new CardBeans(objects.getString("display_value"), objects.getString("display_field"),false));
                    }

                    emotion_evaluate= json.getJSONArray("emotion_evaluate");  //情绪评估
                    for (int sss=0;sss<emotion_evaluate.length();sss++){
                        JSONObject objects=emotion_evaluate.getJSONObject(sss);
                        objects.getString("display_field");
                        cardItemsss.add(new CardBeans(objects.getString("display_value"), objects.getString("display_field"),false));
                        objects.getString("display_value");
                    }


                    mAdapter = new TeAdapter(Edu_upload_test_Activity.this,cardItem);
                    spinner0.setAdapter(mAdapter);
                    spinner0.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                            //拿到被选择项的值

                            String city = mAdapter.getItem(position).getId();

                            String cardNo = mAdapter.getItem(position).getCardNo();

                            if (!cardNo.equals("十必谈")){
                                mAdapter_t = new TeAdapter(Edu_upload_test_Activity.this,cardItem_NO);
                                spinner01.setAdapter(mAdapter_t);
                                spinner01.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                    @Override
                                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                        inter.setTalkType("");

                                    }

                                    @Override
                                    public void onNothingSelected(AdapterView<?> parent) {

                                    }
                                });
                            }else {
                                mAdapter_t = new TeAdapter(Edu_upload_test_Activity.this,cardItem_);
                                spinner01.setAdapter(mAdapter_t);
                                spinner01.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                    @Override
                                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                        //拿到被选择项的值
                                        String city = mAdapter_t.getItem(position).getId();


                                        //把该值传给 TextView
                                        inter.setTalkType(city);

                                    }

                                    @Override
                                    public void onNothingSelected(AdapterView<?> parent) {

                                    }
                                });
                            }

                            //把该值传给 TextView
                            inter.setTalkClassify(city);

                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {

                        }
                    });
                    mAdapter_t = new TeAdapter(Edu_upload_test_Activity.this,cardItem_);
                    spinner01.setAdapter(mAdapter_t);
                    spinner01.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                            //拿到被选择项的值
                            String city = mAdapter_t.getItem(position).getId();


                            //把该值传给 TextView
                            inter.setTalkType(city);

                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {

                        }
                    });

                    mAdapters = new TeAdapter(Edu_upload_test_Activity.this,cardItems);
                    spinner1.setAdapter(mAdapters);
                    spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                            //拿到被选择项的值
//                            str = (String) spinner1.getSelectedItemPosition();
                            String city = mAdapters.getItem(position).getId();
                            String cardNo = mAdapters.getItem(position).getCardNo();

                            //把该值传给 TextView
                            inter.setDangerEvaluate(city);

                            if (cardNo.equals("正常")){
                                mAdapters_ = new TeAdapter(Edu_upload_test_Activity.this,cardItem_NO);
                                spinner11.setAdapter(mAdapters_);
                                spinner11.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                    @Override
                                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                        inter.setDangerAction("");

                                    }

                                    @Override
                                    public void onNothingSelected(AdapterView<?> parent) {

                                    }
                                });
                            }else {
                                mAdapters_ = new TeAdapter(Edu_upload_test_Activity.this,cardItem_ss);
                                spinner11.setAdapter(mAdapters_);
                                spinner11.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                    @Override
                                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                                        //拿到被选择项的值
//                            str = (String) spinner1.getSelectedItemPosition();
                                        String city = mAdapters_.getItem(position).getId();


                                        //把该值传给 TextView
                                        inter.setDangerAction(city);

                                    }

                                    @Override
                                    public void onNothingSelected(AdapterView<?> parent) {

                                    }
                                });
                            }


                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {

                        }
                    });


                    mAdapters_ = new TeAdapter(Edu_upload_test_Activity.this,cardItem_ss);
                    spinner11.setAdapter(mAdapters_);
                    spinner11.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                            //拿到被选择项的值
//                            str = (String) spinner1.getSelectedItemPosition();
                            String city = mAdapters_.getItem(position).getId();

                            //把该值传给 TextView
                            inter.setDangerAction(city);

                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {

                        }
                    });

                    mAdapterss = new TeAdapter(Edu_upload_test_Activity.this,cardItemss);
                    spinner2.setAdapter(mAdapterss);
                    spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                            //拿到被选择项的值
//                            str = (String) spinner1.getSelectedItemPosition();
                            String city = mAdapterss.getItem(position).getId();
                            //把该值传给 TextView
                            inter.setTalkEffect(city);

                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {

                        }
                    });

                    mAdaptersss = new TeAdapter(Edu_upload_test_Activity.this,cardItemsss);
                    spinner3.setAdapter(mAdaptersss);
                    spinner3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                            //拿到被选择项的值
//                            str = (String) spinner1.getSelectedItemPosition();
                            String city = mAdaptersss.getItem(position).getId();
                            //把该值传给 TextView
                            inter.setEmotionEvaluate(city);

                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {

                        }
                    });

                    break;
                case 200:
                    loadingDialog.dismiss();
                    Edu_upload_test_Activity.this.finish();

                    break;
            }

        } catch (JSONException e) {

        }

    }




    private void startTalk() {



        mLayoutRecord.setVisibility(View.VISIBLE);
        mLayoutPlay.setVisibility(View.GONE);
//        voiceManager.sessionRecord(false);

        resolveRecord();

    }





    /**
     * 开始录音
     */
    private void resolveRecord() {
        filePath = FileUtils.getAppPath();
        File file = new File(filePath);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                Toast.makeText(Edu_upload_test_Activity.this, "创建文件失败", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        filePath = FileUtils.getAppPath() + UUID.randomUUID().toString() + ".mp3";
        mRecorder = new MP3Recorder(new File(filePath));
//        int size = getScreenWidth(getActivity()) / dip2px(getActivity(), 1);//控件默认的间隔是1
      /*  mRecorder.setDataList(audioWave.getRecList(), size);
        mRecorder.setErrorHandler(new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == MP3Recorder.ERROR_TYPE) {
                    Toast.makeText(getActivity(), "没有麦克风权限", Toast.LENGTH_SHORT).show();
                    resolveError();
                }
            }
        });*/

        //audioWave.setBaseRecorder(mRecorder);

        try {
            mRecorder.start();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(Edu_upload_test_Activity.this, "录音出现异常", Toast.LENGTH_SHORT).show();
            return;
        }
    }

    /**
     * 停止录音
     */
    private void resolveStopRecord() {
        if (mRecorder != null && mRecorder.isRecording()) {
            mRecorder.setPause(false);
            mRecorder.stop();
        }
    }


    private void send_edu_data() {



        voiceManager.clickRecordFinish();


        inter.setCusNumber("3223");
        inter.setPrisonerId(persionId);
        inter.setPrisonerName(prisoner_name);
        inter.setPoliceId(police_id);
        inter.setPoliceName(police_name);
        inter.setDepartmentId(department_id);
        inter.setDepartmentName(department_name);
        inter.setTalkTime(now_time);
        inter.setTalkTimeLong(String.valueOf(TimeUtils.getTimeSpanByNow(TimeUtils.getNowString(),MSEC)));
        String data=new Gson().toJson(inter);
        getP().uploadData(data,mRecPath);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        voiceManager.stopMedia_play(new MediaPlayer(),true);



    }
}
